package cn.ibizlab.util.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Set;

@Component
@Slf4j
public class CacheStore {

    private static CacheStore _instance ;

    @PostConstruct
    public void init() {
        _instance = this;
    }

    public static CacheStore getInstance() {
        return _instance;
    }


    @Value("${ibiz.cacheLevel:L1}")
    private String cacheLevel;

    @Autowired
    @Lazy
    private RedisTemplate redisTemplate;

    public void clearL2ByPattern(String pattern) {
        if ("L2".equalsIgnoreCase(cacheLevel)) {
            try {
                Set<String> keys = redisTemplate.keys(pattern);
                if (keys != null && !keys.isEmpty()) {
                    redisTemplate.delete(keys);
                    log.info("L2 cache clear: " + keys);
                }
            } catch (Exception ex) {

            }
        }
    }
}
